<template>
    <Header />
    <div class="equipment-container">
        <div class="equipment">
            <div class="button-container">
                <el-button type="primary" @click="handleAdd">添加设备</el-button>
            </div>
            <div class="table">
                <el-table :data="paginatedData" border style="width: 90%" :header-cell-style="{ textAlign: 'center' }"
                    :cell-style="{ textAlign: 'center' }" @sort-change="handleSortChange">
                    <el-table-column prop="greenhouseName" label="所属大棚" sortable></el-table-column>
                    <el-table-column prop="name" label="设备名称" sortable></el-table-column>
                    <el-table-column label="状态" sortable>
                        <template #default="scope">
                            <el-switch v-model="scope.row.status" active-value="1" inactive-value="0"
                                @change="handleChangeStatus(scope.row)"></el-switch>
                        </template>
                    </el-table-column>
                    <el-table-column prop="createTime" label="创建日期" sortable>
                        <template #default="scope">
                            {{ formatDate(scope.row.createTime) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="startTime" label="启动时间" sortable>
                        <template #default="scope">
                            {{ formatDate(scope.row.startTime) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="endTime" label="停止时间" sortable>
                        <template #default="scope">
                            {{ formatDate(scope.row.endTime) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="运行时间" sortable>
                        <template #default="scope">
                            {{ scope.row.formattedRuntime }}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作">
                        <template #default="scope">
                            <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
                            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                    :current-page="currentPage" :page-sizes="[20, 50, 100]" :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper" :total="equipments.length"
                    style="margin-top: 20px; text-align: center;"></el-pagination>
            </div>

            <!-- 新增/编辑对话框 -->
            <el-dialog :title="dialogTitle" v-model="dialogVisible" width="30%">
                <el-form :model="form" label-width="100px">
                    <el-form-item label="所属大棚">
                        <el-select v-model="form.greenhouseId" placeholder="请选择大棚">
                            <el-option v-for="item in greenhouse" :key="item.id" :label="item.name"
                                :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="设备名称">
                        <el-input v-model="form.name"></el-input>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="dialogVisible = false">取 消</el-button>
                        <el-button type="primary" @click="handleConfirm">确 定</el-button>
                    </span>
                </template>
            </el-dialog>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onBeforeUnmount } from 'vue';
import Header from '@/components/Header.vue';
import { get } from '@/api/request';
import { ElMessage } from 'element-plus';

const equipments = ref([]);
const greenhouse = ref([]);
const form = reactive({
    id: null,
    greenhouseId: null,
    name: '',
});
const dialogVisible = ref(false);
const dialogTitle = ref('');

const formatDate = (date) => {
    return date ? new Date(date).toLocaleDateString() : '';
};

const formatRuntime = (runtime, isRunning, startTime) => {
    console.log('formatRuntime called with:', { runtime, isRunning, startTime }); // 添加调试输出
    if (!runtime) return '';

    const [years, months, days, hours, minutes, seconds] = runtime.split('/').map(Number);

    if (isRunning && startTime) {
        const now = new Date();
        const timeDifference = now.getTime() - new Date(startTime).getTime();
        const diffSeconds = Math.floor(timeDifference / 1000);
        const diffMinutes = Math.floor(diffSeconds / 60);
        const diffHours = Math.floor(diffMinutes / 60);
        const diffDays = Math.floor(diffHours / 24);
        const diffMonths = Math.floor(diffDays / 30);
        const diffYears = Math.floor(diffDays / 365);

        const totalSeconds = seconds + diffSeconds;
        const totalMinutes = minutes + Math.floor(totalSeconds / 60);
        const totalHours = hours + Math.floor(totalMinutes / 60);
        const totalDays = days + Math.floor(totalHours / 24);
        const totalMonths = months + Math.floor(totalDays / 30);
        const totalYears = years + Math.floor(totalDays / 365);

        const finalSeconds = totalSeconds % 60;
        const finalMinutes = totalMinutes % 60;
        const finalHours = totalHours % 24;
        const finalDays = totalDays % 30;
        const finalMonths = totalMonths % 12;
        const finalYears = totalYears;

        return formatEffectiveRuntime(finalYears, finalMonths, finalDays, finalHours, finalMinutes, finalSeconds);
    } else {
        return formatEffectiveRuntime(years, months, days, hours, minutes, seconds);
    }
};

const formatEffectiveRuntime = (years, months, days, hours, minutes, seconds) => {
    if (years > 0) {
        return `${years}年${months}月${days}天`;
    } else if (months > 0) {
        return `${months}月${days}天${hours}小时`;
    } else if (days > 0) {
        return `${days}天${hours}小时${minutes}分钟`;
    } else if (hours > 0) {
        return `${hours}小时${minutes}分钟${seconds}秒`;
    } else if (minutes > 0) {
        return `${minutes}分钟${seconds}秒`;
    } else {
        return `${seconds}秒`;
    }
};

const currentPage = ref(1);
const pageSize = ref(20);

const sortOptions = ref({ prop: '', order: '' });

const paginatedData = computed(() => {
    let sortedData = [...equipments.value];
    if (sortOptions.value.prop) {
        sortedData.sort((a, b) => {
            const isAsc = sortOptions.value.order === 'ascending';
            if (isAsc) {
                return a[sortOptions.value.prop] > b[sortOptions.value.prop] ? 1 : -1;
            } else {
                return a[sortOptions.value.prop] < b[sortOptions.value.prop] ? 1 : -1;
            }
        });
    }

    const start = (currentPage.value - 1) * pageSize.value;
    const end = start + pageSize.value;
    return sortedData.slice(start, end);
});

const fetchequipments = async () => {
    try {
        const response = await get('/equipment/selectAll');
        if (response.status === 200) {
            const data = response.data.data;
            console.log('Fetched data:', data); // 添加调试输出
            // 提取所有大棚的设备信息
            const allEquipments = data.flatMap(greenhouse => {
                return greenhouse.equipments.map(equipment => ({
                    ...equipment,
                    greenhouseName: greenhouse.greenhouseName || `大棚 ${greenhouse.greenhouseId}`,
                    formattedRuntime: formatRuntime(equipment.totalRuntime, equipment.status === '1', equipment.startTime)
                }));
            });
            equipments.value = allEquipments;
        } else {
            ElMessage.error(response.data.message || '获取数据失败');
        }
    } catch (error) {
        ElMessage.error('请求失败，请检查网络');
        console.error('请求失败:', error);
    }
};

const fetchGreenhouses = async () => {
    try {
        const response = await get('/greenhouse/selectAll');
        if (response.status === 200) {
            console.log(response.data)
            greenhouse.value = response.data.data;
        } else {
            ElMessage.error(response.data.message || '获取数据失败');
        }
    } catch (error) {
        ElMessage.error('请求失败，请检查网络');
        console.error('请求失败:', error);
    }
};

const updateRuntimes = () => {
    equipments.value.forEach(equipment => {
        if (equipment.status === '1') {
            equipment.formattedRuntime = formatRuntime(equipment.totalRuntime, true, equipment.startTime);
        }
    });
};

let timer = null;

onMounted(() => {
    fetchequipments();
    fetchGreenhouses();
    timer = setInterval(updateRuntimes, 1000); // 每秒钟更新一次运行时间
});

onBeforeUnmount(() => {
    clearInterval(timer); // 清除定时器
});

const handleAdd = () => {
    dialogTitle.value = '添加设备';
    Object.assign(form, {
        id: null,
        greenhouseId: null,
        name: '',
    });
    dialogVisible.value = true;
};

const handleEdit = (row) => {
    dialogTitle.value = '编辑设备';
    Object.assign(form, row);
    dialogVisible.value = true;
};

const handleConfirm = async () => {
    try {
        if (form.id) {
            // 编辑操作
            const response = await get('/equipment/update', form);
            if (response.status === 200) {
                ElMessage.success('编辑成功');
            } else {
                ElMessage.error(response.data.message || '编辑失败');
            }
        } else {
            // 新增操作
            const response = await get('/equipment/add', form);
            if (response.status === 200) {
                ElMessage.success('新增成功');
            } else {
                ElMessage.error(response.data.message || '新增失败');
            }
        }
        // 重新获取设备列表
        fetchequipments();
        // 关闭对话框
        dialogVisible.value = false;
    } catch (error) {
        ElMessage.error('操作失败，请检查网络');
        console.error('操作失败:', error);
    }
};

const handleDelete = async (row) => {
    try {
        const response = await get(`/equipment/delete?id=${row.id}`);
        if (response.status === 200) {
            ElMessage.success('删除成功');
            // 重新获取设备列表
            fetchequipments();
        } else {
            ElMessage.error(response.data.message || '删除失败');
        }
    } catch (error) {
        ElMessage.error('操作失败，请检查网络');
        console.error('操作失败:', error);
    }
};

const handleChangeStatus = async (row) => {
    try {
        const response = await get(`/equipment/updateStatus?id=${row.id}&status=${row.status}`);
        if (response.status === 200) {
            // 重新获取设备列表
            fetchequipments();
            ElMessage.success('状态更新成功');
        } else {
            ElMessage.error(response.data.message || '状态更新失败');
            // 如果更新失败，恢复原来的状态
            row.status = row.status === '1' ? '0' : '1';
        }
    } catch (error) {
        ElMessage.error('操作失败，请检查网络');
        console.error('操作失败:', error);
        // 如果请求失败，恢复原来的状态
        row.status = row.status === '1' ? '0' : '1';
    }
};

const handleSizeChange = (newSize) => {
    pageSize.value = newSize;
};

const handleCurrentChange = (newPage) => {
    currentPage.value = newPage;
};

const handleSortChange = (column) => {
    sortOptions.value = {
        prop: column.prop,
        order: column.order
    };
};
</script>

<style lang="scss" scoped>
$primary-green: #67c23a;
$secondary-green: #b7eb8f;

.equipment-container {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    margin-top: 100px;
}

.equipment {
    max-width: 1500px;
    width: 100%;
    padding: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    background-color: #fff;
    border-radius: 4px;
}

.button-container {
    text-align: right;
    margin-bottom: 10px;
}

.el-table tbody tr:hover {
    background-color: #f5f5f5;
}

.table {
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
}

.el-table {

    th,
    td {
        color: $primary-green;
    }

    .el-button--primary {
        background-color: $primary-green;
        border-color: $primary-green;
    }

    .el-button--primary:hover {
        background-color: darken($primary-green, 10%);
        border-color: darken($primary-green, 10%);
    }
}

.el-pagination {

    .btn-prev,
    .btn-next,
    .number,
    .more {
        color: $primary-green;
    }

    .btn-prev:hover,
    .btn-next:hover,
    .number:hover {
        color: darken($primary-green, 10%);
    }

    .el-pager li.active {
        color: white;
        background-color: $primary-green;
    }
}
</style>